package transactions.dq.master;

import transactions.dq.StringUtilForName;
import dinamica.Db;
import dinamica.Recordset;
import dinamica.StringUtil;

public class FenHu extends dinamica.audit.AuditableTransaction{

	public int service(Recordset inputParams) throws Throwable {
		int rc = super.service(inputParams);

		Db db = getDb();
		
		//查询出新户主的信息
		String newMaster = getSQL(getResource("query_master_detail.sql"), inputParams);
		Recordset rs = db.get(newMaster);
		rs.next();

		// 插入t_master
		String sqlInsertMaster = getResource("insert.sql");
		sqlInsertMaster = getSQL(sqlInsertMaster, inputParams);

		// 汉字名字转换成字母存放在master_chars
		String master_name = rs.getString("user_name");
		String charsStr = StringUtilForName.getFirstLetter(master_name);
		sqlInsertMaster = StringUtil.replace(sqlInsertMaster,"${master_name}", master_name);
		sqlInsertMaster = StringUtil.replace(sqlInsertMaster,"${master_chars}", charsStr);

		db.exec(sqlInsertMaster);

		// (1)修改t_master_detail
		String members = inputParams.getString("memberid");
		if(members != null && members.length()>0){
			String ids[] = members.split(";");
			String sqlUpdateMasterDetail = getResource("update_detail.sql");
			sqlUpdateMasterDetail = getSQL(sqlUpdateMasterDetail, inputParams);
			for(int i=0;i<ids.length;i++){
				if("".equals(ids[i]) || inputParams.getString("master_tuid").equals(ids[i])){
					continue;
				}
				sqlUpdateMasterDetail = StringUtil.replace(sqlUpdateMasterDetail, "${tuid}", ids[i]);
				db.exec(sqlUpdateMasterDetail);
			}
		}
		//修改新户主的信息
		String sqlUpdateMaster = getResource("update_master_detail.sql");
		sqlUpdateMaster = getSQL(sqlUpdateMaster, inputParams);
		db.exec(sqlUpdateMaster);
		
		//修改新旧户主的人口信息
		db.exec(getSQL(getResource("update-old-population.sql"), inputParams));
		db.exec(getSQL(getResource("update-new-population.sql"), inputParams));

		return rc;
	}
}
